package com.cheyunkeji.er.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.CountDownTimer;
import android.os.IBinder;

/**
 * 倒计时全局后台处理服务
 */
public class CountDownService extends Service {

    // 60s 倒计时
    public static final long MILLIS_IN_FUTURE = 60 * 1000L;


    private OnCountChangedAction mAction;

    private CountDownTimer mCountDownTimer;

    private volatile long curMillis = 0L;

    public class MyBinder extends Binder {
        public CountDownService getService() {
            return CountDownService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
    }

    @Override
    public void onCreate() {
        super.onCreate();

        // 最大60s，间隔1秒的倒计时
        mCountDownTimer = new CountDownTimer(MILLIS_IN_FUTURE, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                curMillis = millisUntilFinished;

                if (mAction != null)
                    mAction.onTick(millisUntilFinished);
            }

            @Override
            public void onFinish() {
                curMillis = 0;

                if (mAction != null)
                    mAction.onFinish();

                // 结束
                stopSelf();
            }
        };
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 手动启动计数
        start();
        return Service.START_NOT_STICKY;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        mAction = null;

        return true;
    }

    @Override
    public void onDestroy() {
        stop();
        super.onDestroy();
    }

    // 停止计时
    private void stop() {
        mCountDownTimer.cancel();
        mAction = null;
    }

    // 开始计时
    private void start() {
        mCountDownTimer.start();
    }

    public long getCurMillis() {
        return curMillis;
    }

    public void setOnCountChangedAction(OnCountChangedAction action) {
        this.mAction = action;
    }

    /**
     * 计数变化监听
     */
    public interface OnCountChangedAction {

        /**
         * @see CountDownTimer#onTick(long)
         */
        void onTick(long millisUntilFinished);

        /**
         * @see CountDownTimer#onFinish()
         */
        void onFinish();
    }
}
